
package org.example.rubbish.service.impl;

import com.qcloud.cos.region.Region;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.rubbish.config.COSConfig;
import org.example.rubbish.service.COSService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
public class COSServiceImpl implements COSService {
    @Autowired
    private  COSConfig cosConfig;

    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        // 初始化COS客户端
        COSClient cosClient = createCOSClient();

        try {
            // 生成唯一文件名
            String fileName = generateUniqueFileName(file.getOriginalFilename());

            // 获取文件输入流
            try (InputStream inputStream = file.getInputStream()) {
                // 设置对象元数据
                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setContentLength(file.getSize());
                objectMetadata.setContentType(file.getContentType());

                // 创建上传请求
                PutObjectRequest putObjectRequest = new PutObjectRequest(
                        cosConfig.getBucketName(),
                        fileName,
                        inputStream,
                        objectMetadata
                );

                // 执行上传
                cosClient.putObject(putObjectRequest);

                // 返回完整的文件访问URL
                return cosConfig.getDomain() + "/" + fileName;
            }

        } catch (CosClientException e) {
            throw new IOException("文件上传失败: " + e.getMessage());
        } finally {
            if (cosClient != null) {
                cosClient.shutdown();
            }
        }
    }

    @Override
    public void deleteFile(String fileUrl) {
        if (fileUrl == null || !fileUrl.startsWith(cosConfig.getDomain())) {
            return;
        }

        // 从完整URL中提取文件名
        String fileName = fileUrl.substring(cosConfig.getDomain().length() + 1);

        COSClient cosClient = createCOSClient();

        try {
            cosClient.deleteObject(cosConfig.getBucketName(), fileName);
        } catch (CosClientException e) {
        } finally {
            if (cosClient != null) {
                cosClient.shutdown();
            }
        }
    }

    @Override
    public String generateUniqueFileName(String originalFileName) {
        // 生成时间目录
        String timeDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

        // 生成唯一文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");

        // 获取文件扩展名
        String extension = "";
        if (originalFileName != null && originalFileName.contains(".")) {
            extension = originalFileName.substring(originalFileName.lastIndexOf("."));
        }

        return "products/" + timeDir + "/" + uuid + extension;
    }

    /**
     * 创建COS客户端
     */
    private COSClient createCOSClient() {
        // 初始化用户身份信息
        COSCredentials cred = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());

        // 设置bucket的区域
        Region region = new Region(cosConfig.getRegion());

        // 客户端配置
        ClientConfig clientConfig = new ClientConfig(region);

        // 生成cos客户端
        return new COSClient(cred, clientConfig);
    }
}